package org.zhuxian.cn.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;
import org.zhuxian.cn.result.JsonResult;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/image")
@Api(tags = "图片管理", description = "base64转图片链接")
public class ImageController {
    @Value("${file.temp-dir:/tmp/images}")
    private String tempDir;

    @Value("${server.ip:123.249.43.156}")
    private String serverIp;

    @Value("${server.port:18080}")
    private int serverPort;

    @PostMapping("/upload")
    @ApiOperation(value = "base64 转 图片链接", notes = "上传图片base64转本地图片，仅保留10分钟")
    public JsonResult<String> upload(@RequestBody String base64Data) {
        try {
            // 检查配置信息
            if (tempDir == null || tempDir.isEmpty() || serverIp == null || serverIp.isEmpty()) {
                log.error("Missing configuration: tempDir or serverIp");
                return new JsonResult<>(500, "Missing configuration", null);
            }

            // 解析 Base64 数据
            String[] parts = base64Data.split(",");
            if (parts.length < 2) {
                log.error("Invalid base64 data format");
                return new JsonResult<>(400, "Invalid base64 data format", null);
            }
            byte[] imageBytes = Base64Utils.decodeFromString(parts[1]);

            // 生成文件名
            String fileName = UUID.randomUUID() + "_" + System.currentTimeMillis() + ".jpg";
            Path path = Paths.get(tempDir, fileName);

            // 创建目录
            Files.createDirectories(path.getParent());

            // 写入文件
            Files.write(path, imageBytes);

            // 构建图片链接
            String imageUrl = "http://" + serverIp + ":" + serverPort + "/temp-images/" + fileName;
            return new JsonResult<>(200, "OK", imageUrl);
        } catch (IOException e) {
            log.error("Error saving image to disk", e);
            return new JsonResult<>(500, "Error saving image to disk", null);
        } catch (Exception e) {
            log.error("Unexpected error occurred", e);
            return new JsonResult<>(500, "Unexpected error occurred", null);
        }
    }
}